<template>
    <div>
        <el-row class="mb-4">
            <el-button color="#626aef" @click="openPhoneReview">预览</el-button>
            <el-button color="#626aef" @click="save">保存</el-button>
            <el-button color="#626aef" @click="goBack">返回</el-button>
        </el-row>
        <div :class="phoneReviewClass">
            <div class="close" @click="closePhoneReview"></div>
            <PhoneHtml :htmlContent="htmlContentStr" />
        </div>
        <div>
            <el-input v-model="senceName" placeholder="景点名称" />
        </div>
        <div style="border: 1px solid #ccc">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" :defaultConfig="editorConfig" :mode="mode"
                @onCreated="handleCreated" />
        </div>
        <div class="app-container">
            <div style="background-color: #ffffff;">
                <div id="container"></div>
            </div>
            <table>
                <tr>
                    <td>
                        <label>请输入关键字：</label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <input id="tipinput" />
                    </td>
                </tr>
            </table>
        </div>
    </div>
</template>

<script>

import AMapLoader from '@amap/amap-jsapi-loader';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeMount, onBeforeUnmount, shallowRef, ref, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import PhoneHtml from './PhoneHtml.vue'
import { useRoute } from 'vue-router'
import { getScenicInfo } from '../request/apiRequest'
export default {
    name: "TextEdit",
    components: { Editor, Toolbar, PhoneHtml },
    setup () {
        // 编辑器实例，必须用 shallowRef
        const editorRef = shallowRef()
        const route = useRoute()
        let senceName = ref('')
        const toolbarConfig = {}
        const editorConfig = reactive({
            placeholder: '景点详情介绍...',
            MENU_CONF: {
                uploadImage: {
                    server: 'http://101.43.43.184:8083/admin/scenic/saveSnapshot',
                    fieldName: 'scenicSnapshots',
                    // 单个文件上传失败
                    onFailed (file, res) {           // JS 语法
                        if (res.code != 200) {
                            editorRef.value.alert('上传图片失败', 'error')

                        }
                    },
                    customInsert (res, insertFn) {                  // JS 语法
                        // res 即服务端的返回结果
                        if (res.code != 200) {
                            editorRef.value.alert('上传图片失败', 'error')
                        } else {
                            const url = "http://101.43.43.184:8083" + res.data[0]
                            // 从 res 中找到 url alt href ，然后插入图片
                            insertFn(url, "", "")
                        }


                    },
                },

            }
        })
        const senceLocaltion = reactive({ lat: 0, lng: 0 })


        onBeforeMount(() => {
            getScenicInfo(route.query.id).then((data) => {
                console.log(data.data)
                senceName.value = data.data.name
                const editor = editorRef.value
                editor.setHtml(data.data.description)
                senceLocaltion.lat = data.data.lat
                senceLocaltion.lng = data.data.lng

                gaoDeMap()
            });

        })


        // 组件销毁时，也及时销毁编辑器
        onBeforeUnmount(() => {
            const editor = editorRef.value
            if (editor == null) return
            editor.destroy()
        })

        const handleCreated = (editor) => {
            editorRef.value = editor // 记录 editor 实例，重要！
        }
        let htmlContentStr = ref("");
        const save = () => {
            const editor = editorRef.value
            console.log(editor.getHtml())
            htmlContentStr.value = editor.getHtml()
        }
        let phoneReviewClass = ref("phone-review-none")


        const closePhoneReview = () => {
            phoneReviewClass.value = "phone-review-none"
        }

        const openPhoneReview = () => {
            htmlContentStr.value = editorRef.value.getHtml()
            phoneReviewClass.value = "phone-review"
            console.log("htmlContentStr" + htmlContentStr.value)
        }

        const goBack = () => {
            window.history.back();
        }


        const dialogImageUrl = ref('')
        const dialogVisible = ref(false)

        const handleRemove = (uploadFile, uploadFiles) => {
            console.log(uploadFile, uploadFiles)
        }

        const handlePictureCardPreview = (uploadFile) => {
            dialogImageUrl.value = uploadFile.url
            dialogVisible.value = true
        }

        const gaoDeMap = () => {
            window._AMapSecurityConfig = {
                securityJsCode: 'a032271b069417b98c60ec057ac7ee49',
            }
            AMapLoader.load({
                key: "9bf4a78b5982035179ef0bc39c051067", // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                // plugins:[''], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            }).then((AMap) => {
                console.log(senceLocaltion.lat, senceLocaltion.lng)
                const current_position = ref([senceLocaltion.lng, senceLocaltion.lat]);
                const map = new AMap.Map("container", {  //设置地图容器id
                    viewMode: "3D",    //是否为3D地图模式
                    zoom: 13,           //初始化地图级别
                    center: [senceLocaltion.lng, senceLocaltion.lat], //初始化地图中心点位置
                });
                // 添加插件
                AMap.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.Geolocation", "AMap.MapType", "AMap.MouseTool", "AMap.PlaceSearch"], function () {
                    //异步同时加载多个插件
                    // 添加地图插件
                    map.addControl(new AMap.ToolBar()); // 工具条控件;范围选择控件
                    map.addControl(new AMap.Scale()); // 显示当前地图中心的比例尺
                    map.addControl(new AMap.HawkEye()); // 显示缩略图
                    map.addControl(new AMap.Geolocation()); // 定位当前位置
                    map.addControl(new AMap.MapType()); // 实现默认图层与卫星图,实时交通图层之间切换
                    addMarker()
                });
                // 单击
                map.on('click', (e) => {
                    // lng ==> 经度值  lat => 维度值
                    current_position.value = [e.lnglat.lng, e.lnglat.lat];
                    addMarker();
                })

                //输入提示
                var autoOptions = {
                    input: "tipinput"
                };

                AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
                    var auto = new AMap.AutoComplete(autoOptions);
                    var placeSearch = new AMap.PlaceSearch({
                        map: map
                    });  //构造地点查询类
                    auto.on("select", select);//注册监听，当选中某条记录时会触发
                    function select (e) {
                        placeSearch.setCity(e.poi.adcode);
                        placeSearch.search(e.poi.name, function (status, result) {
                            //搜索成功时，result 即是对应的匹配数据
                            console.log(result);
                        });  //关键字查询查询
                    }

                });
                // 实例化点标记
                // 第一种(封成函数来触发)
                function addMarker () {
                    const marker = new AMap.Marker({
                        icon: new AMap.Icon({
                            size: new AMap.Size(19, 31),//图标大小  
                            imageSize: new AMap.Size(19, 31),
                            image: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
                            imageOffset: new AMap.Pixel(0, 0)
                        }),
                        //这里用/img/loc.png图片的left:18;top:38指向坐标
                        offset: new AMap.Pixel(-9, -31),
                        position: current_position.value,
                        // draggable: false //点标记可拖拽
                    });
                    marker.setMap(map);
                }
            }).catch(e => {
                console.log(e);
            })


        }


        return {
            editorRef,
            mode: 'default', // 或 'simple'
            toolbarConfig,
            editorConfig,
            senceName,
            handleCreated,
            save,
            htmlContentStr,
            phoneReviewClass,
            closePhoneReview,
            openPhoneReview,
            goBack,
            handleRemove,
            handlePictureCardPreview
        };
    }

}
</script> 
<style scoped>
.el-row {
    margin-bottom: 10px;
}

.phone-review {
    background-color: aliceblue;
    position: absolute;
    left: 50%;
    top: 48%;
    width: 500px;
    height: 890px;
    margin-top: -400px;
    margin-left: -200px;
    z-index: 999;
}

.phone-review-none {
    display: none;
}

.close:before,
.close:after {
    content: "";
    position: absolute;
    right: 10px;
    width: 2px;
    height: 20px;
    background-color: #333;
}

.close:before {
    transform: rotate(45deg);
}

.close:after {
    transform: rotate(-45deg);
}

.sence-image {
    margin-top: 30px;
}

.sence-image-text {
    margin-bottom: 10px;
    font-size: large;
}


#container {
    margin-top: 20px;
    width: 100%;
    height: 300px;
}
</style>   